package tool

import (
	"encoding/base64"
	"guard/internal/conf"
	"os"
)

type Img struct {
	Base64Pic         string
	ImgFileName       string
	ImgLocalFile      string
	ImgNginxServerUrl string
}

func NewImg(picBase64Str string, username string) *Img {
	return &Img{
		Base64Pic:         picBase64Str,
		ImgFileName:       username + ".jpg",
		ImgLocalFile:      conf.Conf.Img.ImgLocalUrl,
		ImgNginxServerUrl: conf.Conf.Img.ImgNginxServer,
	}
}

// StoreImgLocal 存储图片到本地
func (i *Img) StoreImgLocal() (string, error) {
	// 直接覆盖，将base64位图片转码，存储到本地，返回头像url，因为有可能是用户更新头像
	// 1.转换base64位的图片
	bytes, err := base64.StdEncoding.DecodeString(i.Base64Pic)
	if err != nil {
		return "", err
	}
	// 2.io字节流，输出到本地目录
	err = os.WriteFile(i.ImgLocalFile+i.ImgFileName, bytes, 0644)
	if err != nil {
		return "", err
	}
	return i.ImgNginxServerUrl + i.ImgFileName, nil
}
